package base

import (
	"gitee.com/slion/infra"
	"github.com/sirupsen/logrus"
	"os"
	"os/signal"
	"reflect"
	"syscall"
)

// 函数类型的切片
var callback []func()

// 注册回调函数
func Register(fn func()){
	callback = append(callback, fn)
}

type HookStarter struct {
	infra.BaseStarter
}

// 接受信号,触发回调
func (s *HookStarter) Init(ctx infra.StartContext) {
	sign := make(chan os.Signal)
	signal.Notify(sign, syscall.SIGQUIT, syscall.SIGTERM)
	go func() {
		for {
			// 阻塞
			c := <-sign
			logrus.Infof("notify is [%s]", c.String())
			for _, fn := range callback{
				fn()
			}
			break
		}
		// os.Exit(0)
	}()
}

// 注册所有starter的Stop()方法
func (s *HookStarter) Start(ctx infra.StartContext) {

	starters := infra.GetStarters()
	for _, starter := range starters {
		typ := reflect.TypeOf(starter)
		logrus.Infof("Register Notify Stop %s.Stop()", typ.String())
		Register(func() {
			starter.Stop(ctx)
		})
	}
}